﻿using System.Collections.Generic;

namespace DbFrame.DbContext.SqlServer.Achieve.Query
{
    using System.Linq;
    using System.Data;
    using DbFrame.BaseClass;
    using DbFrame.Core.Abstract;
    using DbFrame.Core.Abstract.Query;
    using DbFrame.Core.CodeAnalysis;
    using DbFrame.Core.Interface.Query;

    public class MappingDataAchieve<T> : AbstractMappingData<T>
    {
        public MappingDataAchieve(SQL _Sql, AbstractAdo _Ado, Analysis _Analysis)
        {
            this.Ado = _Ado;
            this.SqlCode = _Sql;
            this.analysis = _Analysis;
        }

        public override int Count()
        {
            return this.analysis.Count(this.SqlCode);
        }

        public override IMappingData Distinct()
        {
            this.analysis.CreateDistinct(this.SqlCode);
            return this;
        }

        public override T Frist()
        {
            return this.Frist<T>();
        }

        public override TReturn Frist<TReturn>()
        {
            this.Top(1);

            this.ToSql();
            var _T = this.Ado.QueryFirstOrDefault<TReturn>(this.SqlCode.Code.ToString(), this.SqlCode.GetDynamicParameters());
            if (_T == null)
                return Parser.CreateInstance<TReturn>();
            return _T;
        }

        public override List<DbParam> GetDbParam()
        {
            return this.SqlCode.Parameter;
        }

        public override IMappingData TakePage(int PageNumber, int PageSize)
        {
            this.analysis.CreateTakePage(this.SqlCode, PageNumber, PageSize);
            return this;
        }

        public override List<T> ToList()
        {
            return this.ToList<T>();
        }

        public override List<TReturn> ToList<TReturn>()
        {
            this.ToSql();

            var _List = this.Ado.QueryBySql<TReturn>(this.SqlCode.Code.ToString(), this.SqlCode.GetDynamicParameters()).ToList();
            if (_List == null)
                return new List<TReturn>();
            return _List;
        }

        public override IMappingData Top(int Top)
        {
            this.analysis.CreateTop(Top, this.SqlCode);
            return this;
        }

        public override SQL ToSql()
        {
            Analysis.ToSql(this.SqlCode, this.Ado.CommitState);

            return this.SqlCode;
        }

        public override DataTable ToTable()
        {
            this.ToSql();

            return this.Ado.QueryDataTable(this.SqlCode.Code.ToString(), this.SqlCode.GetDynamicParameters());
        }



    }
}
